<template>
  <a-modal
    :destroy-on-close="true"
    :mask-closable="false"
    :visible="visible"
    title="编辑文件"
    :confirm-loading="loading"
    @cancel="handleClose"
    @ok="handleSubmit"
  >
    <a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-item label="文件名称" name="fileName">
        <a-input v-model:value="formData.fileName" placeholder="请输入文件名称" />
      </a-form-item>
      <a-form-item label="文件分组" name="groupId">
        <a-tree-select
          v-model:value="formData.groupId"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="groupTreeData"
          placeholder="请选择文件分组"
          tree-default-expand-all
        >
        </a-tree-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script name="AttachFileEdit" lang="ts" setup>
import { getFile, updateFile } from "@/api/content/attachFile";

const emit = defineEmits(["reload"]);
const title = ref("编辑文件");
const loading = ref(false);
const visible = ref(false);

const selectDataSource = inject<any>("selectDataSource");

const formRef = ref();
const formData: any = reactive({
  fileId: undefined,
  fileName: ""
});
const formRules = reactive({
  fileName: [{ required: true, trigger: "blur", message: "请输入文件名称" }]
});

const handleGetFile = (id: number) => {
  loading.value = true;
  getFile(id)
    .then(response => {
      Object.assign(formData, response.data);
    })
    .finally(() => {
      loading.value = false;
    });
};

const groupTreeData = ref<any>([]);
const handleGetList = () => {
  if (groupTreeData.value.length <= 0) {
    const selectItems: any = [
      {
        title: "未分组",
        key: 0,
        value: 0
      }
    ];

    groupTreeData.value =
      selectDataSource != undefined && selectDataSource.value != undefined
        ? selectItems.concat(selectDataSource.value)
        : selectItems;
  }
};
const handleEdit = (id: number) => {
  handleGetFile(id);
  handleGetList();
  visible.value = true;
};

const handleClose = () => {
  formData.fileId = 0;
  formRef.value.resetFields();
  visible.value = false;
};

const handleSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      updateFile(formData)
        .then(() => {
          antdMessage.success("编辑成功");
          emit("reload");
          handleClose();
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(error => {
      console.log("error", error);
    });
};
defineExpose({ handleEdit });
</script>
